package com.shop.cereshop.agent.controller.voucher;

import com.shop.cereshop.agent.page.user.CereAgentUserVO;
import com.shop.cereshop.agent.param.voucher.PickVoucherDTO;
import com.shop.cereshop.agent.param.wallet.WalletPayDTO;
import com.shop.cereshop.agent.service.voucher.AgentVoucherUserService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户代金券接口
 */
@RequestMapping("voucher/user")
@RestController
@Api(value = "AgentVoucherUserController", tags = "用户代金券接口")
public class AgentVoucherUserController {

  @Autowired
  private AgentVoucherUserService agentVoucherUserService;



  @ApiOperation(value = "购买代金券接口")
  @PostMapping("buy")
  public Result<Void> buyVoucher(@RequestBody @Valid WalletPayDTO param, HttpServletRequest request) throws CoBusinessException {
      CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
      if (user == null) {
          return Result.unauthorized();
      }
      try {
          //解密
          param = param.decrypt();
      } catch (Exception e) {
          return new Result<>(CoReturnFormat.PARAM_INVALID);
      }
      agentVoucherUserService.buyVoucher(param, user.getAgentUserId());
      return Result.success();
  }

  @ApiOperation(value = "代理商选择不同城市代理接口")
  @PostMapping("pick")
  public Result<Void> pickCity(@RequestBody @Valid PickVoucherDTO pickVoucherDTO, HttpServletRequest request) throws CoBusinessException {
      CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
      if (user == null) {
          return Result.unauthorized();
      }
      pickVoucherDTO.setAgentUserId(user.getAgentUserId());
      //代理商绑定城市
      Integer row = agentVoucherUserService.pickCity(pickVoucherDTO);
      return row > 0 ? Result.success() : Result.failed(CoReturnFormat.FAIL, "选择城市失败");
  }
}
